package com.hctforgreen.greenservice.ui.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.DownloadManagerActivityV2;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookListEntity;
import com.hctforgreen.greenservice.model.DataVersionCodeEntity;
import com.hctforgreen.greenservice.model.SerieListEntity;
import com.hctforgreen.greenservice.service.TechnicalDataUpdateService;
import com.hctforgreen.greenservice.utils.DataVersionCodeUtil;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.FileCacheUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LogUtil;
import com.umeng.analytics.MobclickAgent;

import com.hctforgreen.greenservice.threeLevelList.Node;
import com.hctforgreen.greenservice.threeLevelList.TreeListViewAdapter;

import java.util.ArrayList;
import java.util.List;

import cn.dns.reader.network.Util;

/**
 * 三层列表：下载管理适配器
 * Created by 390694 on 2016/11/24.
 */
public class DownloadManagerAdapter<T> extends TreeListViewAdapter<T> {
    //存储调用updateBookOnWhatClick该方法的操作
    List<BookListEntity.BookEntity> state_On_Click;
    //存储调用updateBookZipState该方法的操作
    List<BookListEntity.BookEntity> bookStateList;

    private Activity mActivity;
    private int refreshType;//更新类型
    public List<T> data;
    private ListView mListView;
    private boolean state = false;

    /**
     * @param mTree
     * @param mActivity
     * @param data
     * @param defaultExpandLevel 默认展开几级树
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public DownloadManagerAdapter(ListView mTree, Activity mActivity, List<T> data,
                                  int defaultExpandLevel,int type,boolean state) throws IllegalArgumentException, IllegalAccessException {
        super(mTree, mActivity, data, defaultExpandLevel);

        receive = new MyReceive();
        /**
         * 390778 2016 12 15
         * 判断是否需要注册广播
         */
        if(!state){
            LogUtil.i("startReceive","adapter注册了广播");
            receive = new MyReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.hctforgreen.greenservice");
            try {
                mActivity.registerReceiver(receive,filter);
            }catch(Exception e){
                LogUtil.i("Exception","e"+e);
            }
        }

        state_On_Click = new ArrayList<BookListEntity.BookEntity>();
        bookStateList = new ArrayList<BookListEntity.BookEntity>();


        this.data = data;
        this.mActivity = mActivity;
        refreshType = type;
        mListView = mTree;
       // initRefreshBtn();
    }



    @Override
    public View getConvertView(final Node node, int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item_download_book_threelevel_lst, null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //设置名称
        viewHolder.getBookNameLyt().setText(node.getBookName());

        //设置显示系列书，书籍数
        if (node.getLevel() == 0) {//第一级
            convertView.setBackgroundColor(mActivity.getResources().getColor(R.color.white));
            hintWidget(viewHolder, node.getLevel());
            String sCount = mActivity.getString(R.string.child_series_count_hint);
            int iCount = (node.getChildren().size() == 0) ? 0
                    : node.getChildren().size();
            sCount = String.format(sCount, iCount);
            viewHolder.getChildSeriesCountTv().setText(sCount);

        } else if (node.getLevel() == 1) {//第二级
            hintWidget(viewHolder, node.getLevel());
            convertView.setBackgroundColor(mActivity.getResources().getColor(R.color.gray_light));
            String sCount = mActivity
                    .getString(R.string.child_series_books_count_hint);
            sCount = String.format(sCount, node.getSeriesCounts());
            viewHolder.getChildSeriesCountTv().setText(sCount);

        } else if (node.getLevel() == 2) {//第三级
            hintWidget(viewHolder, node.getLevel());
            convertView.setBackgroundColor(mActivity.getResources().getColor(R.color.transparent));
            if (!node.getBookSize().equals("")) {
                long lBookFileLongSize = Long.valueOf(node.getBookSize());

                viewHolder.getTVSizeLyt().setTextColor(mActivity.getResources().getColor(R.color.black));
                viewHolder.getTVSizeLyt().setText(FileCacheUtil.FormetFileSize(lBookFileLongSize));
            }
            node.getBookEntity().setNodePosition(position);
            switchButtons(viewHolder.getLyt_book(), node.getBookEntity());
            initProgressBar(viewHolder.getLyt_book(), node.getBookEntity());

            initButtons(viewHolder.getLyt_book(), node.getBookEntity());
        }
        return convertView;
    }

    /**
     * 根据当前Node携带的BookEntity查找本地数据库中的Book
     *
     * @param node
     * @return
     */
    public BookListEntity.BookEntity getDbBookEntity(Node node) {
        if (node.getLevel() != 2 || node.getBookEntity() == null)
            return null;
        final String bookId = node.getBookEntity().id;
        DbController dbController = new DbController(mActivity);
        BookListEntity.BookEntity entity = dbController.getBookEntity(bookId);
        return entity;
    }

    class ViewHolder {
        private View baseView;
        private LinearLayout lyt_book;
        ImageView img;//收起/展开图片
        TextView tv_name;//名称
        TextView tv_downloaded_size;
        TextView tv_size_header;
        TextView tv_size;//书籍大小

        TextView tv_download_done;//已下载
        TextView childSeriesCountTv;//已下载
        TextView tv_download_waiting;//正在排队
        TextView tv_has_update_zip;//资料有更新
        Button btn_download;//下载
        Button btn_cancel;//取消
        Button btn_update;//更新
        Button btn_delete;//删除
        Button btn_analysis;//正在解析
        ProgressBar pb_download;


        public ViewHolder(View view) {
            this.baseView = view;
        }

        public LinearLayout getLyt_book() {
            if (lyt_book == null) {
                lyt_book = (LinearLayout) baseView.findViewById(R.id.lyt_book);
            }
            return lyt_book;
        }

        public ImageView getImgLyt() {
            if (img == null) {
                img = (ImageView) baseView.findViewById(R.id.expand_img);
            }
            return img;
        }

        public TextView getBookNameLyt() {
            if (tv_name == null) {
                tv_name = (TextView) baseView.findViewById(R.id.tv_three_level_name);
            }
            return tv_name;
        }

        public TextView getDownloadDoneLyt() {
            if (tv_download_done == null) {
                tv_download_done = (TextView) baseView.findViewById(R.id.tv_three_level_download_done);
            }
            return tv_download_done;
        }

        public TextView getChildSeriesCountTv() {
            if (childSeriesCountTv == null) {
                childSeriesCountTv = (TextView) baseView.findViewById(R.id.tv_three_level_child_series_count);
            }
            return childSeriesCountTv;
        }

        public TextView getDownloadWaitingLyt() {
            if (tv_download_waiting == null) {
                tv_download_waiting = (TextView) baseView.findViewById(R.id.tv_three_level_download_waiting);
            }
            return tv_download_waiting;
        }

        public TextView getHasUpdateZipLyt() {
            if (tv_has_update_zip == null) {
                tv_has_update_zip = (TextView) baseView.findViewById(R.id.tv_three_level_has_update_zip);
            }
            return tv_has_update_zip;
        }

        public TextView getDownloadedSizeLyt() {
            if (tv_downloaded_size == null) {
                tv_downloaded_size = (TextView) baseView.findViewById(R.id.tv_three_level_downloaded_size);
            }
            return tv_downloaded_size;
        }

        public TextView getSizeHeaderLyt() {
            if (tv_size_header == null) {
                tv_size_header = (TextView) baseView.findViewById(R.id.tv_three_level_size_header);
            }
            return tv_size_header;
        }

        public TextView getTVSizeLyt() {
            if (tv_size == null) {
                tv_size = (TextView) baseView.findViewById(R.id.tv_three_level_size);
            }
            return tv_size;
        }

        public Button getDownloadLyt() {
            if (btn_download == null) {
                btn_download = (Button) baseView.findViewById(R.id.btn_three_level_download);
            }
            return btn_download;
        }

        public Button getCancelLyt() {
            if (btn_cancel == null) {
                btn_cancel = (Button) baseView.findViewById(R.id.btn_three_level_cancel);
            }
            return btn_cancel;
        }

        public Button getUpdateLyt() {
            if (btn_update == null) {
                btn_update = (Button) baseView.findViewById(R.id.btn_three_level_update);
            }
            return btn_update;
        }

        public Button getDeleteLyt() {
            if (btn_delete == null) {
                btn_delete = (Button) baseView.findViewById(R.id.btn_three_level_delete);
            }
            return btn_delete;
        }

        public Button getAnalysisLyt() {
            if (btn_analysis == null) {
                btn_analysis = (Button) baseView.findViewById(R.id.btn_three_level_analysis);
            }
            return btn_analysis;
        }

        public ProgressBar getPbDownloadLyt() {
            if (pb_download == null) {
                pb_download = (ProgressBar) baseView.findViewById(R.id.pb_three_level_download);
            }
            return pb_download;
        }

    }

    public List<T> getMList() {
        return data;
    }

    /**
     * 判断层级，隐藏控件
     *
     * @param level
     */
    private void hintWidget(ViewHolder viewHolder, int level) {
        if (level == 0) {
            viewHolder.getDownloadDoneLyt().setVisibility(View.GONE);
            viewHolder.getChildSeriesCountTv().setVisibility(View.VISIBLE);
            viewHolder.getTVSizeLyt().setVisibility(View.GONE);
            viewHolder.getImgLyt().setVisibility(View.VISIBLE);
            viewHolder.getDownloadLyt().setVisibility(View.GONE);
            viewHolder.getDeleteLyt().setVisibility(View.GONE);
            viewHolder.getCancelLyt().setVisibility(View.GONE);
            viewHolder.getAnalysisLyt().setVisibility(View.GONE);
            viewHolder.getUpdateLyt().setVisibility(View.GONE);
        } else if (level == 1) {

            viewHolder.getTVSizeLyt().setVisibility(View.GONE);
            viewHolder.getDownloadDoneLyt().setVisibility(View.GONE);
            viewHolder.getChildSeriesCountTv().setVisibility(View.VISIBLE);
            viewHolder.getImgLyt().setVisibility(View.VISIBLE);
            viewHolder.getDownloadLyt().setVisibility(View.GONE);
            viewHolder.getDeleteLyt().setVisibility(View.GONE);
            viewHolder.getCancelLyt().setVisibility(View.GONE);
            viewHolder.getAnalysisLyt().setVisibility(View.GONE);
            viewHolder.getUpdateLyt().setVisibility(View.GONE);
        } else {
            viewHolder.getDownloadLyt().setVisibility(View.VISIBLE);
            viewHolder.getChildSeriesCountTv().setVisibility(View.GONE);
            viewHolder.getTVSizeLyt().setVisibility(View.VISIBLE);
            viewHolder.getImgLyt().setVisibility(View.INVISIBLE);
        }
    }




    private void initButtons(final View bookLyt, final BookListEntity.BookEntity entity) {

        if (entity == null)
            return;
        final DbController dbController = new DbController(mActivity);
        /**
         * 下载
         */
        Button downloadBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_download);
        downloadBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(mActivity, "Account_download");
                entity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_DOWNLOAD_CLICK;
                /**
                 * 2016 12 16
                 * 390778  增加判断--更新到数据库，防止数据库锁住
                 */
               state = DownloadBookLstInitFinishUtil.getDownloadBookFinished(mActivity);
                if(state){
                    dbController.updateBookOnWhatClick(entity);
                }else{
                    state_On_Click.add(entity);
                }
                LogUtil.i("state","点击下载   当前状态为："+state);
                /**
                 * 调用Service下载
                 */
                Util.doDownloadBook(mActivity, entity,state);
            }
        });
        /**
         * 取消
         */
        Button cancelBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_cancel);
        cancelBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(mActivity, "Account_cancel_download");

                cancelWhenServiceUnConnection(bookLyt, entity, dbController);

                ((DownloadManagerActivityV2) mActivity).getConnection()
                        .cancelDownloadingUrl(entity.download_url);

            }
        });
        /**
         * 更新
         */
        Button updateBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_update);
        updateBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                MobclickAgent.onEvent(mActivity, "Account_update_download");

                entity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK;


                /**
                 * 2016 12 16
                 * 390778  增加判断--更新到数据库，防止数据库锁住
                 */
                state = DownloadBookLstInitFinishUtil.getDownloadBookFinished(mActivity);
                LogUtil.i("state","点击更新   当前状态为："+state);
                if(state){
                    dbController.updateBookOnWhatClick(entity);
                }else{
                    state_On_Click.add(entity);
                }

                /**
                 * 调用Service下载
                 */
                Util.doDownloadBook(mActivity, entity);
            }
        });
        /**
         * 删除
         */
        Button deleteBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_delete);
        deleteBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(mActivity, "Account_delete_download");
                entity.bookZipState = HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_DELETE;
                DbController dbController = new DbController(mActivity);

                /**
                 * 2016 12 16
                 * 390778  增加判断--更新到数据库，防止数据库锁住
                 */
                state = DownloadBookLstInitFinishUtil.getDownloadBookFinished(mActivity);
                LogUtil.i("state","点击删除    当前状态为："+state);
                if(state){
                    dbController.updateBookZipState(entity);
                }else{
                    bookStateList.add(entity);
                }

                Util.tryToDeleteBook(entity, mActivity);
                // mSelf.notifyDataSetChanged();
                switchButtons(bookLyt, entity);
                /*//刷新界面，把其他子系列下面同一本书的状态刷新为一样的
                ((DownloadManagerActivityV2) mActivity).initDataLst(0,false);*/

            }
        });
        /**
         * 解析中
         */
        Button analysisBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_analysis);
        analysisBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!((DownloadManagerActivityV2) mActivity).getConnection()
                        .isBeingDownloaded(entity.download_url)
                        && !entity.doWhatClick
                        .equals(HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK)) {
                    /**
                     * 2016 12 15
                     * 390778
                     * 增加状态判断
                     * true  进行数据库操作
                     * false  进行保存到list中，等待操作完成后进行插入数据库
                     */
                    if(state){
                        updateBookZipState(
                                entity,
                                HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL);
                    }else{
                        entity.bookZipState = HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL;
                        bookStateList.add(entity);
                    }

                    switchButtons(bookLyt, entity);
                } else if (!((DownloadManagerActivityV2) mActivity)
                        .getConnection().isBeingDownloaded(entity.download_url)
                        && entity.doWhatClick
                        .equals(HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK)) {
                    /**
                     * 2016 12 15
                     * 390778
                     * 增加状态判断
                     * true  进行数据库操作
                     * false  进行保存到list中，等待操作完成后进行插入数据库
                     */
                    if(state){
                        updateBookZipState(
                                entity,
                                HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE);
                    }else{
                        entity.bookZipState = HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE;
                        bookStateList.add(entity);
                    }

                    switchButtons(bookLyt, entity);
                }
            }
        });

    }

    /**
     * @param entity
     * @param downloadedSizeTv
     */
    private void renderDownloadedSize(BookListEntity.BookEntity entity,
                                      TextView downloadedSizeTv) {
        String sUnit = entity.bookFileSize.substring(
                entity.bookFileSize.length() - 1, entity.bookFileSize.length());
        String sAllSize = entity.bookFileSize.substring(0,
                entity.bookFileSize.length() - 1);

        String sDownloadedSize = "%1$.2f" + sUnit;
        sDownloadedSize = String.format(sDownloadedSize,
                Float.valueOf(sAllSize) * entity.progress / 100);

        downloadedSizeTv.setText(sDownloadedSize);

    }

    private void downLoad(final SerieListEntity.ChildSerieEntity cEntity) {
        final DbController dbController = new DbController(mActivity);
        for (int i = 0; i < cEntity.childSeriesBookIdList.size(); i++) {
            final String bookId = cEntity.childSeriesBookIdList.get(i);
            BookListEntity.BookEntity entity = dbController.getBookEntity(bookId);
            /**
             * 未下载||下载失败||已取消||已经删除
             */
            if (entity.bookZipState
                    .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_NONE)
                    || entity.bookZipState
                    .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_FAIL)
                    || entity.bookZipState
                    .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL)
                    || entity.bookZipState
                    .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_DELETE)) {
                MobclickAgent.onEvent(mActivity, "Account_download");

                entity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_DOWNLOAD_CLICK;
                dbController.updateBookOnWhatClick(entity);

                /**
                 * 调用Service下载
                 */
                Util.doDownload(mActivity, entity);

            }
            /**
             * 解析完成&&可以更新
             */
            else if (entity.bookZipState
                    .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE)
                    && entity.bCanUpdate
                    .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_TRUE)) {
                MobclickAgent.onEvent(mActivity, "Account_update_download");

                entity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK;
                dbController.updateBookOnWhatClick(entity);

                /**
                 * 调用Service下载
                 */
                Util.doDownload(mActivity, entity);
            }

        }

    }

    private void switchButtons(final View bookLyt, BookListEntity.BookEntity entity) {
        if (entity == null)
            return;
        /**
         * 进度条
         */
        ProgressBar oneBookPb = (ProgressBar) bookLyt
                .findViewById(R.id.pb_three_level_download);
        /**
         * 下载
         */
        Button downloadBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_download);
        /**
         * 取消
         */
        Button cancelBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_cancel);
        /**
         * 已完成
         */
        TextView doneTv = (TextView) bookLyt
                .findViewById(R.id.tv_three_level_download_done);

        TextView childSeriesCountTv = (TextView) bookLyt
                .findViewById(R.id.tv_three_level_child_series_count);
        /**
         * 解析中
         */
        Button analysisBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_analysis);
        /**
         * 更新
         */
        Button updateBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_update);

        /**
         * 删除
         */
        Button deleteBtn = (Button) bookLyt.findViewById(R.id.btn_three_level_delete);
        /**
         * 有更新包%1$s）
         */
        TextView hasUpdateZipTv = (TextView) bookLyt
                .findViewById(R.id.tv_three_level_has_update_zip);

        /**
         * 已经下载的size
         */
        TextView downloadedSizeTv = (TextView) bookLyt
                .findViewById(R.id.tv_three_level_downloaded_size);

        TextView sizeHeaderTv = (TextView) bookLyt
                .findViewById(R.id.tv_three_level_size_header);
        /**
         * 等待下载
         */
        TextView waitingTv = (TextView) bookLyt
                .findViewById(R.id.tv_three_level_download_waiting);

        /**
         * 未下载 、下载失败
         */
        if (entity.bookZipState
                .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_NONE)
                || entity.bookZipState
                .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_FAIL)) {
            oneBookPb.setVisibility(View.GONE);
            downloadBtn.setVisibility(View.VISIBLE);
            cancelBtn.setVisibility(View.GONE);
            doneTv.setVisibility(View.GONE);
            childSeriesCountTv.setVisibility(View.GONE);
            analysisBtn.setVisibility(View.GONE);
            updateBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);

            hasUpdateZipTv.setVisibility(View.GONE);
            downloadedSizeTv.setVisibility(View.GONE);
            sizeHeaderTv.setVisibility(View.GONE);

            waitingTv.setVisibility(View.GONE);
        }
        /**
         * 正在下载
         */
        else if (entity.bookZipState
                .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_ING)) {
            oneBookPb.setVisibility(View.VISIBLE);
            downloadBtn.setVisibility(View.GONE);
            cancelBtn.setVisibility(View.VISIBLE);
            doneTv.setVisibility(View.GONE);
            childSeriesCountTv.setVisibility(View.GONE);
            analysisBtn.setVisibility(View.GONE);
            updateBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);

            hasUpdateZipTv.setVisibility(View.GONE);
            downloadedSizeTv.setVisibility(View.VISIBLE);
            sizeHeaderTv.setVisibility(View.VISIBLE);

            waitingTv.setVisibility(View.GONE);
        }
        /**
         * 已取消
         */
        else if (entity.bookZipState
                .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL)) {
            oneBookPb.setVisibility(View.GONE);
            downloadBtn.setVisibility(View.VISIBLE);
            cancelBtn.setVisibility(View.GONE);
            doneTv.setVisibility(View.GONE);
            childSeriesCountTv.setVisibility(View.GONE);
            analysisBtn.setVisibility(View.GONE);
            updateBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);

            hasUpdateZipTv.setVisibility(View.GONE);
            downloadedSizeTv.setVisibility(View.GONE);
            sizeHeaderTv.setVisibility(View.GONE);

            waitingTv.setVisibility(View.GONE);
        }
        /**
         * 下载完成
         */
        else if (entity.bookZipState
                .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_DONE)) {
            oneBookPb.setVisibility(View.GONE);
            downloadBtn.setVisibility(View.GONE);
            cancelBtn.setVisibility(View.GONE);
            doneTv.setVisibility(View.VISIBLE);
            childSeriesCountTv.setVisibility(View.GONE);
            analysisBtn.setVisibility(View.GONE);
            updateBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);

            hasUpdateZipTv.setVisibility(View.GONE);
            downloadedSizeTv.setVisibility(View.GONE);
            sizeHeaderTv.setVisibility(View.GONE);

            waitingTv.setVisibility(View.GONE);
        }
        /**
         * 正在解析
         */
        else if (entity.bookZipState
                .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_ING)) {
            oneBookPb.setVisibility(View.GONE);
            downloadBtn.setVisibility(View.GONE);
            cancelBtn.setVisibility(View.GONE);
            doneTv.setVisibility(View.VISIBLE);
            childSeriesCountTv.setVisibility(View.GONE);
            analysisBtn.setVisibility(View.VISIBLE);
            updateBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);

            hasUpdateZipTv.setVisibility(View.GONE);
            downloadedSizeTv.setVisibility(View.GONE);
            sizeHeaderTv.setVisibility(View.GONE);

            waitingTv.setVisibility(View.GONE);
        }
        /**
         * 解析完成
         */
        else if (entity.bookZipState
                .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE)) {
            oneBookPb.setVisibility(View.GONE);
            downloadBtn.setVisibility(View.GONE);
            cancelBtn.setVisibility(View.GONE);
            childSeriesCountTv.setVisibility(View.GONE);
            analysisBtn.setVisibility(View.GONE);

            downloadedSizeTv.setVisibility(View.GONE);
            sizeHeaderTv.setVisibility(View.GONE);

            waitingTv.setVisibility(View.GONE);

            if (entity.bCanUpdate
                    .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_TRUE)) {
                doneTv.setVisibility(View.GONE);

                deleteBtn.setVisibility(View.VISIBLE);
                updateBtn.setVisibility(View.VISIBLE);
                childSeriesCountTv.setVisibility(View.GONE);
                hasUpdateZipTv.setVisibility(View.VISIBLE);

                renderUpdateZipSize(entity, bookLyt);

            } else if (entity.bCanUpdate
                    .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_FALSE)) {
                doneTv.setVisibility(View.VISIBLE);
                childSeriesCountTv.setVisibility(View.GONE);
                deleteBtn.setVisibility(View.VISIBLE);
                updateBtn.setVisibility(View.GONE);

                hasUpdateZipTv.setVisibility(View.GONE);

            }
        }
        /**
         * 已经删除
         */
        else if (entity.bookZipState
                .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_DELETE)) {
            oneBookPb.setVisibility(View.GONE);
            downloadBtn.setVisibility(View.VISIBLE);
            cancelBtn.setVisibility(View.GONE);
            doneTv.setVisibility(View.GONE);
            analysisBtn.setVisibility(View.GONE);
            updateBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);

            hasUpdateZipTv.setVisibility(View.GONE);
            downloadedSizeTv.setVisibility(View.GONE);
            sizeHeaderTv.setVisibility(View.GONE);

            waitingTv.setVisibility(View.GONE);
        }
        /**
         * 等待下载
         */
        else if (entity.bookZipState
                .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_WAITING)) {
            oneBookPb.setVisibility(View.GONE);
            downloadBtn.setVisibility(View.GONE);
            cancelBtn.setVisibility(View.VISIBLE);
            doneTv.setVisibility(View.GONE);
            analysisBtn.setVisibility(View.GONE);
            updateBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);
            childSeriesCountTv.setVisibility(View.GONE);
            hasUpdateZipTv.setVisibility(View.GONE);
            downloadedSizeTv.setVisibility(View.GONE);
            sizeHeaderTv.setVisibility(View.GONE);

            waitingTv.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 当连接不上下载Service时的重置Db中资料的下载状态为"已取消"
     *
     * @param book
     */
    private void cancelWhenServiceUnConnection(final View bookLyt,
                                               final BookListEntity.BookEntity book, final DbController dbController) {
        BookListEntity.BookEntity inDbEntity = dbController
                .getBookEntityUseBookName(book.bookName);

        if (!inDbEntity.doWhatClick
                .equals(HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK)) {
            /**
             * 2016 12 15
             * 390778
             * 增加状态判断
             * true  进行数据库操作
             * false  进行保存到list中，等待操作完成后进行插入数据库
             */
            if(state){
                updateBookZipState(inDbEntity,
                        HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL);
            }else{
                inDbEntity.bookZipState = HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL;
                bookStateList.add(inDbEntity);
            }

            switchButtons(bookLyt, inDbEntity);
        } else if (inDbEntity.doWhatClick
                .equals(HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK)) {
            /**
             * 2016 12 15
             * 390778
             * 增加状态判断
             * true  进行数据库操作
             * false  进行保存到list中，等待操作完成后进行插入数据库
             */
            if(state){
                updateBookZipState(inDbEntity,
                        HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE);
            }else{
                inDbEntity.bookZipState = HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE;
                bookStateList.add(inDbEntity);
            }
            switchButtons(bookLyt, inDbEntity);
        }
    }

    private void renderUpdateZipSize(BookListEntity.BookEntity entity, final View bookLyt) {
        final TextView hasUpdateZipTv = (TextView) bookLyt
                .findViewById(R.id.tv_three_level_has_update_zip);
        String sUpdateZipSize = mActivity
                .getString(R.string.has_update_zip_hint);

        if (!entity.bookFileLongSize.equals("")) {
            long lBookFileLongSize = Long.valueOf(entity.bookFileLongSize);
            sUpdateZipSize = String.format(sUpdateZipSize,
                    FileCacheUtil.FormetFileSize(lBookFileLongSize));
            hasUpdateZipTv.setText(sUpdateZipSize);
        }

        final TextView sizeTv = (TextView) bookLyt.findViewById(R.id.tv_three_level_size);

        try {
            long lCurrentBookFileLongSize = Long
                    .valueOf(entity.currentBookFileLongSize);
            sizeTv.setText(FileCacheUtil
                    .FormetFileSize(lCurrentBookFileLongSize));
        } catch (Exception e) {
        }
    }

    private void updateBookZipState(final BookListEntity.BookEntity bookEntity,
                                    final String state) {
        DbController dbController = new DbController(mActivity);
        bookEntity.bookZipState = state;
        dbController.updateBookZipState(bookEntity);
    }

    private void initProgressBar(final View bookLyt, BookListEntity.BookEntity entity) {
        if (entity == null) {
            return;
        }
        if (entity.progress == 99 || entity.progress == 100) {
            return;
        }

        /**
         * 进度条
         */
        ProgressBar oneBookPb = (ProgressBar) bookLyt
                .findViewById(R.id.pb_three_level_download);
        TextView downloadedSizeTv = (TextView) bookLyt
                .findViewById(R.id.tv_three_level_downloaded_size);
        /**
         * 不等于空说明已下载完
         */
        if (entity.progress < 100 && entity.progress != 0) {

            oneBookPb.setProgress(entity.progress);

            renderDownloadedSize(entity, downloadedSizeTv);
        } else if (entity.progress == 100) {
            oneBookPb.setProgress(entity.progress);

        }

    }

    /**
     * 下载这本书时接收广播更新当前item的状态
     *
     * @param downloadUrl
     */
    public void updateBooksLayout(String downloadUrl, BookListEntity.BookEntity bookEntity) {
        int nodePosition = bookEntity != null ? bookEntity.getNodePosition() : 0;
        Node node = mVisibleNodes.get(nodePosition);

        View visibleView = getViewByPosition(nodePosition, mListView);
        LinearLayout bookLyt = (LinearLayout) visibleView
                .findViewById(R.id.lyt_book);
        BookListEntity.BookEntity tagBook =  node.getBookEntity();
        LogUtil.i("Adapter","准备进入");
        if (tagBook != null && tagBook.download_url.equals(downloadUrl)) {
            //从数据库中
            final DbController dbController = new DbController(mActivity);
            BookListEntity.BookEntity inDbEntity = new BookListEntity.BookEntity();
            if (state){
                LogUtil.i("DATA","后台服务已完成数据插入，从本地数据库找到这本书并显示");
                inDbEntity = dbController
                        .getBookEntityUseBookName(tagBook.bookName);
            }else{
                LogUtil.i("DATA","后台服务还没有完成数据插入，从广播中接收数据显示");
                inDbEntity = bookEntity;
            }

            switchButtons(bookLyt, inDbEntity);
            initProgressBar(bookLyt, inDbEntity);
            if (HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_DONE
                    .equals(inDbEntity.bookZipState)
                    || (HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE
                    .equals(inDbEntity.bookZipState) && inDbEntity.bCanUpdate
                    .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_FALSE))) {
                node.getBookEntity().bookZipState = HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE;
                node.getBookEntity().bCanUpdate = HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_FALSE;
                //刷新界面，把其他子系列下面同一本书的状态刷新为一样的
               /* if (state){
                    ((DownloadManagerActivityV2) mActivity).initDataLst(0,false);
                }*/
            }

        }
    }

    /**
     * 根据位置获取某个item的布局
     *
     * @param position
     * @param listView
     * @return
     */
    public View getViewByPosition(int position, ListView listView) {
        int firstVisiblePosition = mListView.getFirstVisiblePosition();
        int lastVisiblePosition = mListView.getLastVisiblePosition();
        if (position < firstVisiblePosition || position > lastVisiblePosition) {
            return listView.getAdapter().getView(position, null, listView);
        } else {
            final int childIndex = position - firstVisiblePosition;
            return listView.getChildAt(childIndex);
        }
    }

    /**
     * 相应ListView的点击事件 展开或关闭某节点
     *
     * @param position
     */
    public void clickAddChildSeriesBook(List<BookListEntity.BookEntity> childrenBookList, int position) {
        Node convertNode = mVisibleNodes.get(position);
        int indexOf = mAllNodes.indexOf(convertNode);
        List<Node> childListBookNode;

        for (int i = 0; i < childrenBookList.size(); i++) {
            Node newNode = new Node(childrenBookList.get(i).id, childrenBookList.get(i).childSeriesId,
                    childrenBookList.get(i).displayName, childrenBookList.get(i).bookFileLongSize, 0);
            newNode.setBookEntity(childrenBookList.get(i));
            newNode.setIcon(-1);
            newNode.setParent(convertNode);
            convertNode.getChildren().add(newNode);
            mAllNodes.add(indexOf + 1, newNode);

        }
        expandOrCollapse(position);
    }


    //新建等待线程
    class MyThread extends Thread{
        @Override
        public void run() {
            LogUtil.i("test","启动线程");
            final DbController dbController = new DbController(mActivity);
            LogUtil.i("bookStateList","bookStateList的大小"+bookStateList.size());
            for(BookListEntity.BookEntity book : state_On_Click){
                dbController.updateBookOnWhatClick(book);
            }
            for(BookListEntity.BookEntity book : bookStateList){
                dbController.updateBookZipState(book);
            }
			try{
               mActivity.unregisterReceiver(receive);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    private MyReceive receive;

    //广播接收
    class MyReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.i("startReceive","开始接收广播");
            LogUtil.i("liststatebook2","需要进行操作的书的多少"+bookStateList.size());
            LogUtil.i("Adapter中发送广播之前的当前状态state",state+"");
            state = intent.getBooleanExtra("state",false);
            LogUtil.i("Adapter中广播发送的当前状态state",state+"");

            new MyThread().start();
            try {
                mActivity.unregisterReceiver(receive);
            }catch (Exception e){
                LogUtil.i("服务注册", "Receiver not registered"+e);
            }

        }
    }

}
